Page({
  onShow: function () {
    this.onLoad(); // 页面加载时获取积分
  },
  data: {
    avatar: "/resource/images/order/avatarDemo.png",
    name: "小黎",
    phone: "18670299841",
    CouponNumber: null,
    pointsNumber: null,
    userInfo: null,
    nickName: null,
    avatarUrl: null,
    userInfo_tank: false

  },

  onLoad: function () {
    this.setData({
      formattedPhone: this.formatPhone(this.data.phone)
    });
    this.getPointsRecordTotal(); // 页面加载时获取积分
    this.getCoupnsTotal();
  },

  //获取用户可用优惠卷数量
  getCoupnsTotal: function () {
    wx.request({
      url: 'http://localhost:9020/couponIntegral-service/consumer/coupon/my', // 替换为实际的后端地址
      method: 'GET',
      data:{
        status:1
      },
      header: {
        'content-type': 'application/json' // 根据实际情况设置header
      },
      success: (res) => {
        if (res.statusCode === 200) { // 确认响应状态码
          this.setData({
            CouponNumber: res.data.length
          });
        } else {
          console.error('获取优惠卷总数失败:', res);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },

  //获取积分数量
  getPointsRecordTotal: function () {
    wx.request({
      url: 'http://localhost:9020/couponIntegral-service/consumer/points-record-total/getPointsRecordTotal', // 替换为实际的后端地址
      method: 'GET',
      header: {
        'content-type': 'application/json' // 根据实际情况设置header
      },
      success: (res) => {
        if (res.statusCode === 200) { // 确认响应状态码
          const totalPoints = res.data; // 假设后端直接返回了积分总数
          this.setData({
            pointsNumber: totalPoints
          });
        } else {
          console.error('获取积分失败:', res);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },

  formatPhone: function (phone) {
    if (phone.length === 11) {
      return phone.slice(0, 3) + '****' + phone.slice(7);
    }
    return phone;
  },

  goToCouponPage() {
    wx.navigateTo({
      url: '/pages/person/coupns/coupon/coupon',
    });
  },

  goToChannelPage() {
    wx.navigateTo({
      url: '/pages/person/point/exchangeRecords/exchangeRecords',
    });
  },

  goToPointsPage() {
    // 跳转到积分页面，并传递积分数量
    wx.navigateTo({
      url: `/pages/person/point/points/points`,
    });
  },

  goToOrdersPage() {
    wx.navigateTo({
      url: '/pages/person/order/orders/orders',
    });
  },

  goToOfwePage() {
    wx.navigateTo({
      url: '/pages/person/ofwe/ofwe',
    });
  },

  goToOfmePage() {
    wx.navigateTo({
      url: '/pages/person/ofme/ofme',
    });
  },

  goToExchangePage() {
    wx.navigateTo({
      url: '/pages/person/coupns/getCoupons/getCoupons', 
    });
  },

  login() {

  },

  tank(e) {
    if (!this.data.userInfo_tank) {
      // 读取云数据库中存储用户数据的user表格
      wx.cloud.database().collection('user')
        .get()
        .then(res => {
          console.log("用户信息====", res);
          if (res.data.length) {
            this.setData({
              userInfo: res.data[0],
              userInfo_tank: false,
            });
            wx.navigateTo({
              url: '/pages/home/home',
            })
            wx.setStorageSync('user', res.data[0]);
          }
          else {
            console.log("还未注册====", res)
            this.setData({
              userInfo_tank: true
            })
          }
        }).catch(res => {
          console.log('没有在云开发中添加user表')
        })
    } else {
      this.setData({
        userInfo_tank: false
      })
    }

  },
  // 获取微信头像
  onChooseAvatar(e) {
    console.log(e);
    this.setData({
      avatarUrl: e.detail.avatarUrl
    })
  },
  // 获取昵称
  getNickName(e) {
    console.log(e);
    this.setData({
      nickName: e.detail.value
    })
  },
  /**
   * 提交
   */
  submit(e) {
    if (!this.data.avatarUrl) {
      return wx.showToast({
        title: '请选择头像',
        icon: 'error'
      })
    }
    if (!this.data.nickName) {
      return wx.showToast({
        title: '请输入昵称',
        icon: 'error'
      })
    }
    this.setData({
      userInfo_tank: false
    })
    wx.showLoading({
      title: '正在注册',
      mask: 'true'
    })
    let tempPath = this.data.avatarUrl
    let suffix = /\.[^\.]+$/.exec(tempPath)[0];
    console.log(suffix);
    //上传到云存储
    wx.cloud.uploadFile({
      cloudPath: 'userimg/' + new Date().getTime() + suffix, //在云端的文件名称
      filePath: tempPath, // 临时文件路径
      success: res => {
        console.log('上传成功', res)
        let fileID = res.fileID
        wx.hideLoading()
        wx.cloud.database().collection('user')
          .add({
            data: {
              avatarUrl: fileID,
              nickName: this.data.nickName
            }
          }).then(res => {
            let user = {
              avatarUrl: fileID,
              nickName: this.data.nickName
            }
            // 注册成功
            console.log('注册成功')
            wx.navigateTo({
              url: '/pages/home/home',
            })
            wx.setStorageSync('user', user);
            this.setData({
              userInfo: user,
            })
          }).catch(res => {
            console.log('注册失败', res)
            wx.showToast({
              icon: 'error',
              title: '注册失败',
            })
          })

      },
      fail: err => {
        wx.hideLoading()
        console.log('上传失败', res)
        wx.showToast({
          icon: 'error',
          title: '上传头像错误',
        })
      }
    })
  },



});